/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.SequenceFlow;
import com.je.bpm.core.model.process.Process;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.history.HistoricTaskInstance;
import com.je.bpm.engine.impl.HistoricTaskInstanceQueryImpl;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;

import java.util.List;

/**
 * 获取当前节点提交过来个target
 */
public class GetCurrentTargetCmd extends NeedsActiveTaskCmd<String> {

    private static final long serialVersionUID = 1L;

    public GetCurrentTargetCmd(String taskId) {
        super(taskId, null, null);
    }

    @Override
    protected String execute(CommandContext commandContext, TaskEntity task) {
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(task.getProcessDefinitionId());

        Process mainProcess = bpmnModel.getMainProcess();
        String taskKey = task.getTaskDefinitionKey();
        FlowElement flowElement = mainProcess.getFlowElementMap().get(taskKey);
        if (flowElement instanceof KaiteBaseUserTask) {
            KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) flowElement;
            List<SequenceFlow> list = kaiteBaseUserTask.getIncomingFlows();
            if (list.size() == 1) {
                return list.get(0).getId();
            }
            for (SequenceFlow sequenceFlow : list) {
                FlowElement userTask = bpmnModel.getMainProcess().getFlowElement(sequenceFlow.getSourceRef());
                if (userTask != null) {
                    if (getNodeInfo(commandContext, task.getProcessInstanceId(), userTask)) {
                        return sequenceFlow.getId();
                    }
                }
            }
        }
        return "";
    }

    private Boolean getNodeInfo(CommandContext commandContext, String piid, FlowElement userTask) {
        HistoricTaskInstanceQueryImpl historicTaskInstanceQuery = new HistoricTaskInstanceQueryImpl();
        historicTaskInstanceQuery.processInstanceId(piid);
        historicTaskInstanceQuery.taskDefinitionKey(userTask.getId());
        historicTaskInstanceQuery.orderByTaskCreateTime().desc();
        List<HistoricTaskInstance> links = commandContext.getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager()
                .findHistoricTaskInstancesByQueryCriteria(historicTaskInstanceQuery);
        if (links.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected String getSuspendedTaskException() {
        return "Cannot delegate a suspended task";
    }

}
